package com.wushijia.service;

import com.wushijia.model.User;
import com.wushijia.repository.UserRepository;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * description:自定义用户信息
 *
 * @author yang
 * @date 2019/1/22 15:25
 */
@Service
public class CustomizeUserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private UserRepository userRepository;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.getUserByName(username);
    if (user == null) {
      throw new UsernameNotFoundException(username);
    }
    return new MyUserPrincipal(user);
  }

  public final static class MyUserPrincipal extends User implements UserDetails {

    private static final long serialVersionUID = 1L;

    private User user;

    private MyUserPrincipal(User user) {
      super(user);
      this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
      if (user.getRole() == null) {
        return AuthorityUtils.createAuthorityList("ROLE_USER");
      }
      return AuthorityUtils.createAuthorityList(user.getRole().getName() != null ? user.getRole().getName() : "ROLE_USER");
    }

    @Override
    public String getPassword() {
      return user.getPassword();
    }

    @Override
    public String getUsername() {
      return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
      return true;
    }

    @Override
    public boolean isAccountNonLocked() {
      return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
      return true;
    }

    @Override
    public boolean isEnabled() {
      return true;
    }
  }
}
